<script setup lang="ts">
import type {TypeTourInfo} from "~/utils/client";
import useAuthStore from "~/stores/authStore";
import {Textarea} from "~/components/ui/textarea";
import {FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage} from "~/components/ui/form";
import {Input} from "~/components/ui/input";
import {Button} from "~/components/ui/button";
import {useForm} from "vee-validate";
import {toast} from "~/components/ui/toast";

const route = useRoute()
const tourData = ref<TypeTourInfo>()

const authStore = useAuthStore()

const formatDate = (dateString:string) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day}T${hours}:${minutes}`;
}

type TypeForm = {
  name: string,
  label: string,
  placeholder: string,
  type: string,
}

const forms = ref<TypeForm[]>([
  {
    name: 'name',
    label: 'Название',
    placeholder: 'Название тура',
    type: 'text'
  },
  {
    name: 'image',
    label: 'Изображение',
    placeholder: 'Изображение тура',
    type: 'file'
  },
  {
    name: 'departureDate',
    label: 'Дата и время отправления',
    placeholder: '2022-01-01',
    type: 'datetime-local'
  },
  {
    name: 'arrivalDate',
    label: 'Дата и время прибытия',
    placeholder: '2022-01-01',
    type: 'datetime-local'
  },
  {
    name: 'seats',
    label: 'Количество мест',
    placeholder: '30',
    type: 'number'
  },
  {
    name: 'price',
    label: 'Цена с человека',
    placeholder: '1800',
    type: 'number'
  },
])

const imageValue = ref<File>()



const { handleSubmit, setErrors, errors, resetForm} = useForm({})


const submitForm = handleSubmit(async (values) => {
  if (imageValue.value) {
    const reader = new FileReader()
    reader.readAsDataURL(imageValue.value)
    reader.onloadend = async () => {
      values.image = reader.result
      await sendResponse(values)
    }
  }
  else  {
    await sendResponse(values)
  }
  console.log(values)
})

const sendResponse = async (values:any) => {
  if (tourData.value?.id) {
    const {data, error, response} = await client.editTour(tourData.value.id,values)
    if (data) {
      toast({
        title: 'Тур изменен',
        description: 'Тур успешно изменен',
      })
       navigateTo(`/tour/${tourData.value?.id}`)
    }
    if (error) {
      if (response.status === 400) {
        setErrors(error)
        console.log(errors)
      }
      else {
        toast({
          title: 'Произошла ошибка',
          description: error,
        })
      }
    }
  }
}


const getTourInfo = async (id:number) => {
  if (id) {
    let {data, error, response} = await client.getTour(id)
    if (data) {
      data.arrivalDate = formatDate(data.arrivalDate)
      data.departureDate = formatDate(data.departureDate)
      tourData.value = data
      resetForm({
        values: data
      })
      loaderState.value = false
    }
    if (error) {
      console.log(error)
    }
  }
  else {
    navigateTo('/tours')
  }
}
const loaderState = ref(true)
getTourInfo(Number(route.params.id))



</script>

<template>
  <Loader :show="loaderState"/>
  <main class="container flex flex-col justify-start items-center">
    <h2 class="text-3xl">Редактирование Тура</h2>
    <form @submit.prevent="submitForm" class="w-full" :initial-values="values" v-if="tourData">
      <FormField v-for="form in forms" :name="form.name" :key="form.name" v-slot="{ componentField }" :validate-on-input="true" >
        <FormItem v-auto-animate>
          <FormLabel class="flex flex-col gap-2 text-md">
            {{ form.label }}
            <p v-if="form.type === 'file' && !imageValue" class="border border-input bg-background hover:bg-accent hover:text-accent-foreground h-10 px-4 py-2 rounded-md flex justify-start items-center text-sm text-foreground">Выберите изображение</p>
            <p v-if="form.type === 'file' && imageValue" class="border border-input bg-background hover:bg-accent hover:text-accent-foreground h-10 px-4 py-2 rounded-md flex justify-start items-center text-sm text-foreground">{{ imageValue.name }}</p>
          </FormLabel>
          <FormControl>
            <Input :placeholder="form.placeholder" v-bind="componentField" :type="form.type" v-if="form.type !== 'file'"/>
            <Input @change="imageValue = $event.target.files[0];" type="file" class="hidden" v-if="form.type === 'file'" accept="image/*" />
          </FormControl>
          <FormDescription />
          <FormMessage class="text-sm"/>
        </FormItem>
      </FormField>
      <FormField name="description" v-slot="{ componentField }">
        <FormItem v-auto-animate>
          <FormLabel>Описание тура</FormLabel>
          <FormControl class="flex flex-col">
            <LazyGenerateDescription v-bind="componentField"/>
            <Textarea placeholder="Описание тура" v-bind="componentField" class="resize-none h-96"/>
          </FormControl>
          <FormDescription />
          <FormMessage />
        </FormItem>
      </FormField>
      <Button type="submit" class="w-full text-md mt-5">Изменить</Button>
      <Button type="button" class="w-full text-md mt-5" variant="secondary" @click='navigateTo(`/tour/${tourData.id}`)'>Отменить изменение</Button>
    </form>
  </main>
</template>

<style scoped>

</style>